#明文预处理
#初始置换
#16轮F函数
    #每一轮输入轮数，调用子秘钥
    #E盒拓展，轮秘钥异或，S盒替换（压缩），P盒置换
#逆置换
#秘钥生成算法
#加密解密

#F函数一次只处理一个32位二进制明文串
#F函数每次用一个子秘钥--16个子秘钥中的一个

from S_box import func as Substitution

E_box=[32,1,2,3,4,5,
        4,5,6,7,8,9,
        8,9,10,11,12,13,
        12,13,14,15,16,17,
        16,17,18,19,20,21,
        20,21,22,23,24,25,
        24,25,26,27,28,29,
        28,29,30,31,32,1]
#      P置换
P_box=[16,7,20,21,29,12,28,17,
        1,15,23,26,5,18,31,10,
        2,8,24,14,32,27,3,9,
        19,13,30,6,22,11,4,25]


def Extension(bi_text32):
    bi_text48 = ''
    for i in E_box:
        index = i-1
        bi_text48 += str(bi_text32[index])
    return bi_text48

#轮秘钥异或函数
def xor_48(text,key):
    # xor_text = text^key
    xor_text = ''
    for i in range(48):
        xor_text += str(int(text[i])^(int(key[i])))

    return xor_text

#P盒置换
def Permutation(text):  #输入32位，输出32位：二进制字符串
    P_text = ''         #操作方法和E盒相同
    for i in P_box:
        index = i-1
        P_text += str(text[index])
    return P_text



'''
half_text = '10100010
             10100011
             01001101
             01010101'
'''


def func(half_text,reconj_key):
    #E盒拓展√
    half_text = Extension(half_text)  
    # print(half_text)
    #轮密钥异或√
    half_text = xor_48(half_text,reconj_key)  
    # print(half_text)
    #S盒替换√
    half_text = Substitution(half_text)  
    # print('S盒替换后为',half_text)
    #P盒置换√
    half_text = Permutation(half_text)
    # print('P置换完成: ',half_text)

    return half_text

#调用函数示例
# half_text = '11110000101010101111000010101010'
# reconj_key = '000110110000001011101111111111000111000001110010'
# func(half_text,reconj_key)